<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="入库时间" prop="useTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker v-model="createTimeRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="图书名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入图书名称" clearable />
            </el-form-item>            
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:admBookStore:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:admBookStore:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:admBookStore:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown @command="handleMoreCommand"
              v-hasPermi="['system:admBookStore:import', 'system:admBookStore:export', 'system:admBookStore:downloadTemplate']">
              <el-button type="warning" plain size="default">
                导入导出
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="download-template">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">下载模板</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="import-data">
                    <el-icon style="vertical-align: middle">
                      <Upload />
                    </el-icon>
                    <span style="margin-left: 4px">导入数据</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="export-data">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">导出数据</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admBookStoreList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="入库人" align="center" prop="storeId">
          <template #default="scope">
            <span>{{ scope.row.storeName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="storeTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.storeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="编号" align="center" prop="number" />
        <el-table-column label="图书名称" align="center" prop="name">
          <template #default="scope">
            <el-tooltip :content="scope.row.name" placement="top" :disabled="!scope.row.name">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.name }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="出版社" align="center" prop="bookConcern">
          <template #default="scope">
            <el-tooltip :content="scope.row.bookConcern" placement="top" :disabled="!scope.row.bookConcern">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.bookConcern }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="是否借出" align="center" prop="isBorrrow">
          <template #default="scope">
            <!-- 根据 scope.row.isBorrrow 的值显示对应文本 -->
            {{ scope.row.isBorrow === 0 ? '在库中' : (scope.row.isBorrow === 1 ? '已借出' : scope.row.isBorrow) }}
          </template>
        </el-table-column>
        <el-table-column label="是否丢失" align="center" prop="isExist">
          <template #default="scope">
            <!-- 根据 scope.row.isExist 的值显示对应文本 -->
            {{ scope.row.isExist === 0 ? '未丢失' : (scope.row.isExist === 1 ? '已丢失' : scope.row.isExist) }}
          </template>
        </el-table-column>
        <el-table-column label="楼层类型" align="center" prop="type">
          <template #default="scope">
            <!-- 根据 scope.row.type 的值显示对应文本 -->
            {{ scope.row.type === 0 ? '二楼书库' : (scope.row.type === 1 ? '三楼书库' : scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:admBookStore:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:admBookStore:remove']"></el-button>
            </el-tooltip>
            <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改图书入库对话框 -->
    <el-dialog v-model="dialog.visible" title="批量入库图书" width="900px" append-to-body :before-close="cancel">
      <!-- 固定信息 -->
      <el-form ref="fixedFormRef" :rules="rules" :model="form" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库人" prop="storeName">
              <el-input v-model="form.storeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="部门" prop="deptName">
              <el-tree-select v-model="form.deptName" :data="deptTree" placeholder="请选择入库部门"
                :props="{ label: 'label', value: 'id', children: 'children' }" check-strictly filterable
                :default-expand-all="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入库时间" prop="storeTime">
              <el-date-picker v-model="form.storeTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择入库时间"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 动态图书列表 -->
      <div class="book-list">
        <el-button type="primary" size="small" @click="addBook">新增图书</el-button>
        <el-divider></el-divider>

        <el-card v-for="(book, index) in books" :key="book.id" class="book-card" shadow="hover">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>图书 {{ index + 1 }}</span>
            <el-button type="danger" size="small" @click="removeBook(index)">删除</el-button>
          </div>

          <el-form :model="book" :rules="bookRules" :ref="el => setBookFormRef(el as ElFormInstance, book.id)"
            label-width="80px">
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="12">
                <el-form-item label="入库楼层" prop="type">
                  <el-select v-model="book.type" placeholder="请选择楼层" @change="(val) => onTypeChange(book, val, index)">
                    <el-option v-for="opt in typeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图书名称" prop="name">
                  <el-input v-model="book.name" placeholder="请输入图书名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出版社" prop="bookConcern">
                  <el-input v-model="book.bookConcern" placeholder="请输入出版社" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编号" prop="number">
                  <el-input v-model="book.number" placeholder="请输入编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="book.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <div v-if="books.length === 0" class="no-book">请点击“新增图书”添加图书</div>
      </div>

      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitAll">提交入库</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :http-request="handleUploadRequest" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改框 -->
    <el-dialog :title="updateDialog.title" v-model="updateDialog.visible" width="900px" append-to-body>
      <el-form ref="admBookStoreFormRef" :model="form" :rules="rules" label-width="140px" label-position="left"
        style="padding: 20px 0 20px 24px">
        <el-form-item label="编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="图书名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入图书名称" />
        </el-form-item>
        <el-form-item label="出版社" prop="bookConcern">
          <el-input v-model="form.bookConcern" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="入库部门" prop="deptName">
          <el-tree-select v-model="form.deptName" :data="deptTree" placeholder="请选择部门"
            :props="{ label: 'label', value: 'id', children: 'children' }" filterable check-strictly
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="入库时间" prop="storeTime">
          <el-date-picker v-model="form.storeTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择入库时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="入库楼层" prop="type">
          <el-select v-model="form.type" placeholder="请选择入库楼层">
            <el-option v-for="option in typeOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="updateDialogCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'ADM-BOOK-STORE-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置图书入库审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="AdmBookStore" lang="ts">
import { listAdmBookStore, getAdmBookStore, delAdmBookStore, addAdmBookStore, updateAdmBookStore, importBooks, getLatestNumber, searchBooks, batchAddBooks } from '@/api/general/administration/book/store';
import { AdmBookStoreVO, AdmBookStoreQuery, AdmBookStoreForm } from '@/api/general/administration/book/store/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admBookStoreList = ref<AdmBookStoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 表单数据
const books = ref<AdmBookStoreVO[]>([])
// const bookFormRefs = ref([]) // 每本书的 ref
// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();
const bookFormRefs = ref(new Map<string, ElFormInstance | null>())
const lastNumberMap = reactive(new Map<number, number>()) // key: type楼层, value: last number
function setBookFormRef(el: ElFormInstance | null, id: number | string) {
  const key = String(id)
  if (el) {
    bookFormRefs.value.set(key, el)
  } else {
    bookFormRefs.value.delete(key)
  }
}
// 用户信息
const userStore = useUserStore();

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 引入数据字典
const { car_type_options, approval_commit_status } = toRefs<any>(proxy?.useDict('car_type_options', 'approval_commit_status'));

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/info/importData'
});

// 入住期限选择
const typeOptions = [
  {
    value: 0,
    label: '二楼',
  },
  {
    value: 1,
    label: '三楼',
  }
]

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);


const queryFormRef = ref<ElFormInstance>();
const admBookStoreFormRef = ref<ElFormInstance>();


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const updateDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmBookStoreForm = {
  id: undefined,
  storeId: userStore.userId,
  storeName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  storeTime: formatLocalDate(),
  number: undefined,
  name: undefined,
  inital: undefined,
  pinyin: undefined,
  bookConcern: undefined,
  isBorrrow: undefined,
  isExist: undefined,
  type: undefined,
  remark: undefined,
  status: undefined,
}
const data = reactive<PageData<AdmBookStoreForm, AdmBookStoreQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: undefined,
    deptId: undefined,
    storeTime: undefined,
    number: undefined,
    name: undefined,
    inital: undefined,
    pinyin: undefined,
    bookConcern: undefined,
    isBorrrow: undefined,
    isExist: undefined,
    type: undefined,
    status: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "图书名称不能为空", trigger: "blur" }
    ],
    bookConcern: [
      { required: true, message: "出版社不能为空", trigger: "blur" }
    ],
    storeName: [
      { required: true, message: "入库人名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "请选择楼层", trigger: "change" }
    ],
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
    storeTime: [{ required: true, message: '请选择入库时间', trigger: 'change' }]
  }
});

// 动态图书表单校验规则（除了备注，其他都必填）
const bookRules = {
  number: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入图书名称', trigger: 'blur' }],
  bookConcern: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
  type: [{ required: true, message: '请选择楼层', trigger: 'change' }]
  // remark 不做校验
}

const { queryParams, form, rules } = toRefs(data);

/** 查询图书入库列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bSignTime: dateRange.value[0]?.toString(),
        eSignTime: dateRange.value[1]?.toString()
      };
    }
    // 处理排序参数
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmBookStore(params);
    admBookStoreList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  admBookStoreFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined,
    params: {}
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmBookStoreVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加图书入库";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmBookStoreVO) => {
  if(row.status != 4){
    ElMessage.error('只能对审核不通过的信息进行修改！');
    return;
  }
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getAdmBookStore(_id);
  Object.assign(form.value, res.data);
  updateDialog.visible = true;
  updateDialog.title = "修改图书入库";
}


/** 修改提交按钮 */
const submitForm = () => {
  admBookStoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmBookStore(form.value).finally(() => buttonLoading.value = false);
        // 调用重置审核流程接口
        await resetApprovalStatus('ADM-BOOK-STORE-AUDIT', Number(form.value.id), '不可审核')
      } else {
        // await addAdmBookStore(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      updateDialog.visible = false;
      await getList();
    }
  });
}

// 监听对话框关闭
watch(approvalFlowVisible, async (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 对话框从显示变成隐藏时刷新列表
    await getList();
  }
});

/** 提交按钮 */
const submitAll = async () => {
  // 1) 先要有书
  if (!books.value.length) {
    ElMessage.warning('请至少添加一本图书后再提交')
    return
  }
  // 2) 校验固定表单
  if (!form.value) {
    ElMessage.error('表单未就绪，请稍后重试')
    return
  }
  // 校验每本书
  let valid = true
  for (const book of books.value) {
    const formRef = bookFormRefs.value.get(String(book.id))
    if (formRef) {
      const ok = await formRef.validate().catch(() => false)
      if (!ok) valid = false
    } else {
      valid = false
    }
  }
  if (!valid) return
  // 封装 payload
  const payload = {
    ...form.value, // 固定信息
    books: books.value // 图书数组
  }
  const res = await batchAddBooks(payload) // 调新接口
  // 触发审核流程配置对话框
  auditIdForApproval.value = res.data;
  approvalFlowVisible.value = true;
  ElMessage.success('批量入库成功')
  dialog.visible = false
  await getList();
  books.value = []
}


/** 删除按钮操作 */
const handleDelete = async (row?: AdmBookStoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除图书入库编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmBookStore(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}




// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
      tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 处理更多命令
const handleMoreCommand = (command: string) => {
  switch (command) {
    case 'download-template':
      handleImportTemplate();
      break;
    case 'import-data':
      upload.open = true; // 打开上传弹窗
      upload.title = '导入图书';
      break;
    case 'export-data':
      handleExport();
      break;
    default:
      break;
  }
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download(
    '/system/admBookStore/downloadTemplate',
    {},
    `book_store_template_${Date.now()}.xlsx`
  );
};

const handleUploadRequest = async (option: any) => {
  if (!option.file) return;
  try {
    upload.isUploading = true;

    // 调用你的接口
    await importBooks(option.file, form.value);

    ElMessage.success('导入成功');
    getList(); // 刷新列表
    option.onSuccess?.({ msg: '导入成功' }, option.file);
  } catch (err: any) {
    ElMessage.error(err?.message || '导入失败');
    option.onError?.(err);
  } finally {
    upload.isUploading = false;
    uploadRef.value?.clearFiles();
    upload.open = false;
  }
};


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/system/admBookStore/export',
    { ...queryParams.value },
    `admBookStore_${Date.now()}.xlsx`
  );
};


/**
 * 提交上传文件
 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/**
 * 文件上传成功处理
 */
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();

  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  // 重新获取列表
  getList();
};

// 在图书新增框中添加图书
const addBook = async () => {
  // 校验固定信息
  if (!form.value.deptId || !form.value.storeTime) {
    ElMessage.warning('请先选择入库部门和入库时间')
    return
  }
  books.value.push({
    id: Date.now(),
    storeId: '',
    storeName: form.value.storeName,
    deptId: form.value.deptId,
    storeTime: form.value.storeTime,
    number: '',
    name: '',
    inital: '',
    pinyin: '',
    bookConcern: '',
    type: null,
    remark: '',
    isExist: undefined,
    isBorrow: undefined,
    createTime: '',
    status: undefined
  })
}

// 删除图书时
const removeBook = (index: number) => {
  const removedBook = books.value.splice(index, 1)[0];
  if (removedBook && removedBook.type !== null && removedBook.type !== undefined) {
    recalcNumbers();
  }
}

// 删除或修改后重新计算编号
const recalcNumbers = async () => {
  // 先分组
  const grouped = books.value.reduce((acc, b) => {
    if (b.type === null || b.type === undefined) return acc;
    if (!acc[b.type]) acc[b.type] = [];
    acc[b.type].push(b);
    return acc;
  }, {} as Record<number, AdmBookStoreForm[]>);

  for (const typeStr in grouped) {
    const type = Number(typeStr);
    const floorBooks = grouped[type];

    // 异步获取最新编号
    const latestNumber = await getLatestNumber(type);

    // 从最新编号开始，依次给每本书编号
    floorBooks.forEach((b, idx) => {
      b.number = String(latestNumber + idx + 1);
    });

    // 更新缓存
    lastNumberMap.set(type, latestNumber + floorBooks.length);
  }
}


// 关闭新增弹窗
const cancel = () => {
  dialog.visible = false
  books.value = []
}

// 关闭修改弹窗
const updateDialogCancel = () => {
  updateDialog.visible = false
  books.value = []
}

// 楼层选择或新增书时调用
const onTypeChange = async (book: AdmBookStoreForm, type: number, index: number) => {
  console.log('楼层选择变化:', book, type, index);
  if (type === null || type === undefined) return;
  // 调用接口获取当前楼层最新编号
  const latestNumber = await getLatestNumber(type);
  // 计算当前楼层已有书本数量（不包括当前这本）
  const sameTypeCount = books.value.filter(b => b.type === type && b !== book).length;
  // 编号 = 接口返回最新编号 + 同楼层已有数量 + 1
  book.number = String(latestNumber + sameTypeCount + 1);
}

// 打开审批弹窗
const openApprovalFlow = (row?: AdmBookStoreVO) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block;
  /* 确保是块级元素 */
}
</style>
